<?php
/**
 * This file is part of easycrm.
 * Author: louxin
 * Date: 14-7-16
 * Time: 下午5:00
 * File: Bulider.php
 */

namespace Icsoc\MenuBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\Routing\Exception\RouteNotFoundException;

/**
 * Class Builder
 * @package Icsoc\MenuBundle\Menu
 */
class Builder extends ContainerAware
{
    /** 需要过滤的菜单 */
    const MENU_BUSNIESS_GROUP = 'icsoc_business_group_index';
    const MENU_BUSNIESS_GROUP_REPORT = 'icsoc_report_group_home';

    private $filterMenu = array(
        'group' => array(
            0 => self::MENU_BUSNIESS_GROUP,
            1 => self::MENU_BUSNIESS_GROUP_REPORT,
        ),
    );

    //所有用户都拥有以下权限 array(1,2,3)
    private $addMenuUrl = array(
        'icsoc_security_develop_download_work_index',
    );

    /**
     * @param FactoryInterface $factory
     * @param array            $options
     * @return \Knp\Menu\ItemInterface
     */
    public function mainMenu(FactoryInterface $factory, array $options)
    {
        $em = $this->container->get('doctrine.orm.default_entity_manager');
        $menus = $em->getRepository('IcsocMenuBundle:Menu')->findAllMenuItems();
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $actionList = $user->getActionList();
        $vccId = $user->getVccId();
        /** @var bool $isEnableGroup  是否启用业务组 */
        $isEnableGroup = $em->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->isEnableGroup($vccId);
        $role = explode(",", $actionList);
        $menu = $factory->createItem(
            'root',
            array(
                'childrenAttributes' => array(
                    'class' => 'nav nav-list',
                ),
            )
        );
        //获得当前的url
        $request = $this->container->get('request');
        $requestUrl = $request->getRequestUri();
        $menuUrl = $request->get('menu_url');
        $menuArray = $this->parseMenus($menus);
        //所有用户都拥有以下权限
        foreach ($this->addMenuUrl as $val) {
            $role[] = $val;
        }
        foreach ($menuArray as $item) {
            $active = $this->isActive($item['url'], $requestUrl, $menuUrl);
            if (!empty($item['url']) && (!in_array($item['url'], $role) && $actionList != 'all')) {
                continue;
            }
            $item['url'] = $this->isValiUrl($item['url']) ? $item['url'] : '';
            $menuItem = $menu->addChild($item['text'], array(
                'routeAbsolute' => true,
                'currentAsLink' => true,
                'childrenAttributes' => array(
                    'class' => 'submenu ',
                ),
                'labelAttributes' => array(
                    'class' => 'menu-text',
                ),
                'extras' => array(
                    'icon' => !empty($item['icon']) ? $item['icon'] : '',
                    'data-url' => $item['url'],
                    'id' => $item['id'],
                ),
                'attributes' => array(
                    'class' => $active ? 'active' : '',
                ),
            ));
            //二级菜单
            if (isset($item['children'])) {
                foreach ($item['children'] as $subItem) {
                    if (!empty($subItem['url']) && !in_array($subItem['url'], $role) && $actionList != 'all') {
                        continue;
                    }

                    /** 未启用业务组过滤掉业务组相关功能 */
                    if (empty($isEnableGroup) && in_array($subItem['url'], $this->filterMenu['group'])) {
                        continue;
                    }

                    $subItem['url'] = $this->isValiUrl($subItem['url']) ? $subItem['url'] : '';
                    $childActive = $this->isActive($subItem['url'], $requestUrl, $menuUrl);
                    if (!$this->container->get("icsoc_core.common.class")->isDisableMenu($subItem['id'], $vccId)) {
                        continue;
                    }
                    $subMenuItem = $menuItem->addChild($subItem['text'], array(
                        'routeAbsolute' => true,
                        'currentAsLink' => true,
                        'childrenAttributes' => array(
                            'class' => 'submenu',
                        ),
                        'labelAttributes' => array(
                            'class' => 'menu-text',
                        ),
                        'extras' => array(
                            'icon' => !empty($subItem['icon']) ? $subItem['icon'] : '' ,
                            'data-url' => $subItem['url'],
                            'id' => $subItem['id'],
                        ),
                        'attributes' => array(
                            'class' => $childActive ? 'active' : '',
                        ),

                    ));
                    if ($childActive) {
                        $menuItem->setAttributes(array('class'=>'active open hsub'));
                    }
                    //三级菜单
                    if (isset($subItem['children'])) {
                        $childrenActive = false;
                        foreach ($subItem['children'] as $thirdItem) {
                            if (!empty($thirdItem['url']) && !in_array($thirdItem['url'], $role) && $actionList != 'all') {
                                continue;
                            }

                            /** 未启用业务组过滤掉业务组相关功能 */
                            if (empty($isEnableGroup) && in_array($thirdItem['url'], $this->filterMenu['group'])) {
                                continue;
                            }

                            $thirdItem['url'] = $this->isValiUrl($thirdItem['url']) ? $thirdItem['url'] : '';
                            $childrenActive = $this->isActive($thirdItem['url'], $requestUrl, $menuUrl);
                            $subMenuItem->addChild($thirdItem['text'], array(
                                'routeAbsolute' => true,
                                'currentAsLink' => true,
                                'childrenAttributes' => array(
                                    'class' => 'submenu',
                                ),
                                'labelAttributes' => array(
                                    'class' => 'menu-text',
                                ),
                                'extras' => array(
                                    'icon' => !empty($thirdItem['icon']) ? $thirdItem['icon'] : '',
                                    'data-url' => $thirdItem['url'],
                                    'id' => $thirdItem['id'],
                                ),
                                'attributes' => array(
                                    'class' => $childrenActive ? 'active' : '',
                                ),
                            ));
                        }
                        if ($childrenActive) {
                            $menuItem->setAttributes(array('class'=>'active open hsub'));
                        }
                    }
                    //没有子类就删除；
                    $subExistChildren = $subMenuItem->getChildren();
                    if (isset($subItem['children']) && empty($subExistChildren)) {
                        $menuItem->removeChild($subItem['text']);
                    }
                }
            }
            $menuExistChildren = $menuItem->getChildren();
            if (isset($item['children']) && empty($menuExistChildren)) {
                $menu->removeChild($item['text']);
            }
        }

        return $menu;
    }

    /**
     * 解析菜单
     *
     * @param array $menus 菜单对象
     * @param int $menuId 父级菜单ID
     * @return array
     */
    public function parseMenus($menus, $menuId = 0)
    {
        $menuArray = array();
        /** @var \Icsoc\MenuBundle\Entity\Menu $item */
        foreach ($menus as $item) {
            $hasChildren = $item->getHasChildren();
            $parentId = $item->getParentId();
            $id = $item->getId();

            if ($parentId == $menuId) {
                $menuArray[$id] = array(
                    'id' => $item->getId(),
                    'text' => $item->getMenuText(),
                    'url' => $item->getMenuUrl(),
                    'icon' => $item->getMenuIcon(),
                );
                if ($hasChildren) {
                    $menuArray[$id]['children'] = $this->parseMenus($menus, $id);
                }
            }
        }

        return $menuArray;
    }

    /**
     * @param $url
     * @param $requestUrl
     * @param string $menuUrl
     * @return bool
     */
    private function isActive($url, $requestUrl, $menuUrl = '')
    {
        $active = false;
        try {
            $generatedUrl = $this->container->get('router')->generate($url);
        } catch (\Exception $e) {
            $generatedUrl = '';
        }

        if (!empty($url) && ($generatedUrl == $requestUrl || $url == $menuUrl)) {
            $active = true;
        }
        return $active;
    }

    /**
     * 检查是否是一个有效的url ;
     * @param $url
     * @return bool
     */
    private function isValiUrl($url)
    {
        try {
            $this->container->get('router')->generate($url);
            return true;
        } catch (RouteNotFoundException $e) {
            return false;
        }
    }
}
